package org.handsomeking.mincroservice.nacos;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Random;

/**
 * @author gaoqijin
 */
@RestController
@RequestMapping("/sentinel")
public class IndexController {

    @Value("${server.port:8888}")
    private int port;

    @Value("${spring:application:name}")
    private String serverName;
    @Autowired
    private RestTemplate restTemplate;


    @GetMapping(value = "/port")
    public String get() {
        return "port : " + port;
    }

    @GetMapping("/sayHi")
    public String sayHi() {
        String body = restTemplate.getForEntity("http://nacos-service1/server1/sayHi", String.class).getBody();
        return body + " >> " + serverName + "sayHi (#^.^#) ";
    }


    @SentinelResource(value = "sentinel/testA" ,blockHandler = "customerBlockHandler" )
    @GetMapping("/testA")
    public String testA() {
        try {
            int i = new Random().nextInt(1000);
            System.out.println(i);
            Thread.sleep(i);
        }catch (Exception e){
        }
        return Thread.currentThread().getId()+"testA!";
    }

    @SentinelResource(value = "sentinel/testB",blockHandler = "customerBlockHandler")
    @GetMapping("/testB")
    public String testB() {
        return Thread.currentThread().getId()+"testB!";
    }

    @SentinelResource(fallback = "fallBackHandler")
    @GetMapping("/testC")
    public String testC() {
        return "testC!";
    }

    @GetMapping("/testD")
    public String testD() {
        return "testD!";
    }

    public String customerBlockHandler(BlockException e) {
        System.out.println("customerBlockHandler!!!");
        return "customerBlockHandler!!!";
    }

    public String customerFallBackHandler(BlockException e) {
        return "customerFallBackHandler!!!";
    }
}
